package com.rainyun.rcmc.own.common;

import com.rainyun.rc.command.CmdUtil;
import com.rainyun.rc.config.ErrorHandler;
import com.rainyun.rc.config.NodeConfig;
import com.rainyun.rc.ioc.Beanzy;
import com.rainyun.rc.ioc.RainIOC;
import com.rainyun.rcmc.bukkit.config.BukYmlConfig;
import com.rainyun.rcmc.bukkit.config.BukYmlNode;
import com.rainyun.rcmc.own.bukkit.controller.CmdRC;
import com.rainyun.rcmc.own.bukkit.main.BukRainCore;
import com.rainyun.rcmc.own.common.BeanRc.BeansRc;
import com.rainyun.rcmc.own.config.RcConfig;
import com.rainyun.rcmc.own.config.RcLang;
import org.bukkit.configuration.ConfigurationSection;
import org.bukkit.configuration.file.YamlConfiguration;

import java.util.Map;
import java.util.logging.Logger;

@Beanzy
public class RcGlobal {

	@BeanRc(BeansRc.Logger)
	Logger logger;
	@Beanzy
	CmdRC cmdRC;

	@BeanRc(BeansRc.Classloader)
	ClassLoader classloader;
	@Beanzy
	BukRainCore plugin;

	public boolean BukReload() {
		
		ErrorHandler eh = (path,e)->{
			logger.info(NodeConfig.getDefaultByEnum(RcLang.reload_error).toString());
			e.printStackTrace();
		};

		BukYmlConfig configManger = new BukYmlConfig(plugin.getDataFolder());
		configManger.setErrorHandler(eh);
		configManger.add(RcConfig.class,"config");
		RainIOC.set(BeansRc.ObjConf,configManger);
		try {
			configManger.loadAllOrNew();
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}
		RcConfig config = configManger.get(RcConfig.class);
		RainIOC.set(BeansRc.Config,config);

		NodeConfig<YamlConfiguration> nodeManger = new BukYmlNode(plugin.getDataFolder(),"",classloader);
		nodeManger.setErrorHandler(eh);
		nodeManger.add("langfiles", "lang/")
				.add("src/src/main/resources/lang","lang/"+config.getLang(),RcLang.class);
		nodeManger.setResource("langfiles",true);
		RainIOC.set(BeansRc.NodeConf,nodeManger);
		try {
			nodeManger.loadAllOrNew();
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}

		YamlConfiguration lang = nodeManger.get("src/src/main/resources/lang");
		ConfigurationSection cmd = lang.getConfigurationSection("cmds");
		Map<String, Object> tree = BukYmlNode.confToMap(cmd);

		CmdUtil.setAttrByTree(RainIOC.get(BeansRc.Cmds),tree,"help");

		return true;
	}

}
